package web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import entity.Risk;
import entity.Role;
import entity.User;
import service.RiskService;

/**
 * Servlet implementation class TracerServlet
 */
public class TracerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final String tracerPage="/view/html/tracer.jsp";
	
	private RiskService riskService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TracerServlet() {
        super();
        riskService=new RiskService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession(false);
		if(session.getAttribute("user")==null||((User)session.getAttribute("user")).getRole()!=Role.RiskTracer){
			return;
		}
		User user=(User)session.getAttribute("user");
		List<Risk> risks=riskService.getRelatedRisk(user.getId());
		session.setAttribute("risks", risks);
		request.getRequestDispatcher(tracerPage).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("riskId")==null||"".equals((String)request.getParameter("riskId"))){
			request.setAttribute("error", "Please select a risk entry.");
			request.getRequestDispatcher(tracerPage).forward(request, response);
			return;
		}else if(request.getParameter("description")==null||"".equals((String)request.getParameter("description"))){
			request.setAttribute("error", "Please fill description.");
			request.getRequestDispatcher(tracerPage).forward(request, response);
			return;
		}
		int id=Integer.parseInt((String)request.getParameter("riskId"));
		String description=(String)request.getParameter("description");
		riskService.updateRisk(id, description);
		response.sendRedirect(request.getContextPath()+"/tracer");
	}

}
